<template>
  <el-drawer v-model="visible" title="用户分配" direction="rtl" size="600px" :before-close="handleClose">
    <div class="drawer-content">
      <div class="role-info">
        <h3>{{ roleData.name }}</h3>
        <p>{{ roleData.description }}</p>
        <el-tag type="info">当前分配用户：{{ selectedUserIds.length }} 人</el-tag>
      </div>

      <el-divider />

      <div class="user-section">
        <div class="section-header">
          <h4>用户列表</h4>
          <div class="search-box">
            <el-input v-model="searchKeyword" placeholder="搜索用户姓名、邮箱..." :prefix-icon="Search" clearable
              style="width: 250px;" />
          </div>
        </div>

        <div class="user-list">
          <el-table ref="userTableRef" :data="filteredUsers" @selection-change="handleSelectionChange"
            style="width: 100%" max-height="400">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="avatar" label="头像" width="60">
              <template #default="{ row }">
                <el-avatar :src="row.avatar" :alt="row.name" size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="email" label="邮箱" min-width="150" />
            <el-table-column prop="department" label="部门" width="100" />
            <el-table-column prop="currentRoles" label="当前角色" min-width="150">
              <template #default="{ row }">
                <div class="role-tags">
                  <el-tag v-for="role in row.currentRoles" :key="role.id" size="small" type="info" class="role-tag">
                    {{ role.name }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.status === '正常' ? 'success' : 'danger'" size="small">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="selection-summary">
          <el-tag type="primary">
            已选择 {{ selectedUserIds.length }} 个用户
          </el-tag>
          <el-button size="small" @click="clearSelection">清空选择</el-button>
          <el-button size="small" @click="selectAll">全选</el-button>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存分配
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  roleData: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const userTableRef = ref()
const submitting = ref(false)
const searchKeyword = ref('')
const selectedUserIds = ref([])

// 模拟用户数据
const allUsers = [
  {
    id: 1,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    name: '张三',
    email: 'zhangsan@example.com',
    department: '技术部',
    status: '正常',
    currentRoles: [{ id: 1, name: '超级管理员' }]
  },
  {
    id: 2,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    name: '李四',
    email: 'lisi@example.com',
    department: '运营部',
    status: '正常',
    currentRoles: [{ id: 2, name: '系统管理员' }]
  },
  {
    id: 3,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    name: '王五',
    email: 'wangwu@example.com',
    department: '教务部',
    status: '禁用',
    currentRoles: [{ id: 3, name: '内容管理员' }]
  },
  {
    id: 4,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    name: '赵六',
    email: 'zhaoliu@example.com',
    department: '市场部',
    status: '正常',
    currentRoles: []
  },
  {
    id: 5,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    name: '钱七',
    email: 'qianqi@example.com',
    department: '人事部',
    status: '正常',
    currentRoles: [{ id: 4, name: '审核员' }]
  }
]

// 计算属性
const visible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

const filteredUsers = computed(() => {
  if (!searchKeyword.value) return allUsers

  return allUsers.filter(user =>
    user.name.includes(searchKeyword.value) ||
    user.email.includes(searchKeyword.value)
  )
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal && props.roleData) {
    // 根据角色获取已分配的用户（模拟数据）
    // 实际项目中这里应该调用API获取
    const assignedUserIds = getAssignedUsers(props.roleData.id)
    selectedUserIds.value = assignedUserIds

    nextTick(() => {
      // 设置表格选中状态
      allUsers.forEach(user => {
        if (assignedUserIds.includes(user.id)) {
          userTableRef.value?.toggleRowSelection(user, true)
        }
      })
    })
  }
})

// 方法
const getAssignedUsers = (roleId) => {
  // 模拟根据角色ID获取已分配的用户ID
  const roleUserMap = {
    1: [1], // 超级管理员 -> 张三
    2: [2, 3], // 系统管理员 -> 李四、王五
    3: [3, 5], // 内容管理员 -> 王五、钱七
    4: [5] // 审核员 -> 钱七
  }
  return roleUserMap[roleId] || []
}

const handleSelectionChange = (selection) => {
  selectedUserIds.value = selection.map(user => user.id)
}

const clearSelection = () => {
  userTableRef.value?.clearSelection()
  selectedUserIds.value = []
}

const selectAll = () => {
  filteredUsers.value.forEach(user => {
    userTableRef.value?.toggleRowSelection(user, true)
  })
}

const handleSubmit = async () => {
  try {
    submitting.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    emit('submit', {
      roleId: props.roleData.id,
      userIds: selectedUserIds.value
    })

    ElMessage.success('用户分配成功')
    handleClose()

  } catch (error) {
    console.error('用户分配失败:', error)
    ElMessage.error('用户分配失败')
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  emit('update:visible', false)
  searchKeyword.value = ''
  selectedUserIds.value = []
}
</script>

<style scoped lang="scss">
.drawer-content {
  padding: 20px;
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.role-info {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 20px;

  h3 {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 16px;
  }

  p {
    margin: 0 0 8px 0;
    color: #666;
    font-size: 14px;
  }
}

.user-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h4 {
      margin: 0;
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }
  }
}

.user-list {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;

  .role-tag {
    margin: 0;
  }
}

.selection-summary {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px 20px 16px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-drawer__title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-divider) {
  margin: 16px 0;
}

:deep(.el-table) {
  .el-table__header {
    background: #f8f9fa;
  }
}
</style>
